import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { CreateAndUpdateRoleDto } from './dto/CreateAndUpdateRoleDto';
import { DeleteDto } from 'src/dto/delete.dto';
import { Roles, RolesDocument } from 'src/db/schemas/roles.schema';
import { QueryRolesDto } from './dto/QueryRolesDto';
import {
  addOne,
  deleteByIds,
  queryPagination,
  toFuzzyParams,
  updateOneById,
} from 'src/utils';

@Injectable()
export class RolesService {
  constructor(
    @InjectModel(Roles.name) private rolesModel: Model<RolesDocument>,
  ) { }

  async addAnyUpdateRole(createAndUpdateRoleDto: CreateAndUpdateRoleDto) {
    const { _id, ...otherParmas } = createAndUpdateRoleDto;
    if (_id) {
      return await updateOneById(this.rolesModel, _id, otherParmas);
    } else {
      return await addOne(this.rolesModel, createAndUpdateRoleDto);
    }
  }

  async getRolePagination(queryRolesDto: QueryRolesDto) {
    const { pageSize, current, off, ...other } = queryRolesDto;
    return await queryPagination(
      this.rolesModel,
      {
        off,
        ...toFuzzyParams(other),
      },
      {
        pageSize,
        current,
      },
    );
  }

  async deleteRoles(deleteDto: DeleteDto) {
    const { ids } = deleteDto;
    return await deleteByIds(this.rolesModel, ids);
  }
}
